<template>
	<div class="padding-container preview-wrap" v-loading.fullscreen.lock="fullscreenLoading">
    <div class="title-part">
		</div>
    <div class="data-preview">
      <el-form class="tab-pan form-inline" size="small" label-position="right" :label-width="formLabelWidth" v-show="isPersonal">
        <el-form-item :label="getLabelPersonal('nickName')">
          <span>{{ baseData.nickName | dataFormat }}</span>
        </el-form-item>
        <el-form-item :label="getLabelPersonal('phoneNum')">
          <span>{{ baseData.phoneNum | dataFormat }}</span>
          <!-- <el-button  class="pull-right edit-button" type="primary" @click="">{{ $root.lang.userinfo.personal.updatePassword }}</el-button> -->
        </el-form-item>
        <el-form-item :label="getLabelPersonal('addDeviceNum')">
          <span>{{ addDeviceNum }}</span>
        </el-form-item>
        <el-form-item :label="getLabelPersonal('installAppNum')">
          <span>{{ installAppNum }}</span>
          <el-button class="pull-right edit-button" type="primary" @click="toBuy('2')" v-show="baseData.isOpen != 1">{{ $root.lang.userinfo.personal.toBuy }}</el-button>
        </el-form-item>
        <el-form-item :label="getLabelEnterprise('visualStatus')">
          <span>{{ baseState.visualStatus, visualStatus, "--" | matchValue }}</span>
          <el-button class="pull-right edit-button" type="primary" @click="toApplyVisual()" v-show="baseData.isOpen != 1 && visualStatus == 0">{{ $root.lang.userinfo.enterprise.toApply }}</el-button>
          <el-button class="pull-right edit-button" type="primary" @click="toBuyVisual()" v-show="baseData.isOpen != 1 && visualStatus == 3">{{ $root.lang.userinfo.personal.toBuy }}</el-button>
        </el-form-item>
        <el-form-item :label="getLabelPersonal('blockStatus')">
          <span v-if="blockStatus == 3">{{ '共' + blockNum + '次' }}</span>
          <span v-else>{{ baseState.blockStatus, blockStatus, "未申请" | matchValue }}</span>
          <el-button class="pull-right edit-button" type="primary" @click="toApplyBlock()" v-show="baseData.isOpen != 1 && blockStatus == 'null'">{{ $root.lang.userinfo.personal.toApply }}</el-button>
          <el-button class="pull-right edit-button" type="primary" @click="toBuyBlock()" v-show="baseData.isOpen != 1 && blockStatus == 3">{{ $root.lang.userinfo.personal.toBuy }}</el-button>
          <el-button class="pull-right edit-button" type="primary" @click="toDownload()" v-show="baseData.isOpen != 1 && blockStatus == 3">{{ $root.lang.userinfo.personal.download }}</el-button>
        </el-form-item>
        <el-form-item :label="getLabelPersonal('logStatus')">
          <span v-if="logExpireTime == 'null'">{{ baseState.logStatus, logStatus, "未申请" | matchValue }}</span>
          <span v-else>{{ logExpireTime | dateFormat }}到期</span>
          <el-button class="pull-right edit-button" type="primary" @click="toApplyLog()" v-show="baseData.isOpen != 1 && logStatus == 'null'">{{ $root.lang.userinfo.personal.toApply }}</el-button>
          <el-button class="pull-right edit-button" type="primary" @click="toBuyLog()" v-show="baseData.isOpen != 1 && logStatus == 3">{{ $root.lang.userinfo.personal.toBuy }}</el-button>
        </el-form-item>
      </el-form>
      <el-form class="tab-pan form-inline" size="small" label-position="right" :label-width="formLabelWidth" v-show="!isPersonal">
        <el-form-item :label="getLabelEnterprise('nickName')">
          <span>{{ baseData.nickName | dataFormat }}</span>
        </el-form-item>
        <el-form-item :label="getLabelEnterprise('enterpriseName')">
          <span>{{ baseData.enterpriseName | dataFormat }}</span>
          <!-- <el-button  class="pull-right edit-button" type="primary" @click="">{{ $root.lang.userinfo.personal.updatePassword }}</el-button> -->
        </el-form-item>
        <el-form-item :label="getLabelEnterprise('businessLicense')">
          <span>{{ baseData.businessLicense | dataFormat }}</span>
        </el-form-item>
        <el-form-item :label="getLabelEnterprise('enterpriseMailbox')">
          <span>{{ baseData.enterpriseMailbox | dataFormat }}</span>
        </el-form-item>
        <el-form-item :label="getLabelEnterprise('contactTelephone')">
          <span>{{ baseData.contactTelephone | dataFormat }}</span>
        </el-form-item>
        <el-form-item :label="getLabelEnterprise('installAppNum')">
          <span>{{ installAppNum }}</span>
          <el-button class="pull-right edit-button" type="primary" @click="toBuy('2')" v-show="baseData.isOpen != 1">{{ $root.lang.userinfo.personal.toBuy }}</el-button>
        </el-form-item>
        <el-form-item :label="getLabelEnterprise('visualStatus')">
          <span>{{ baseState.visualStatus, visualStatus, "--" | matchValue }}</span>
          <el-button class="pull-right edit-button" type="primary" @click="toApplyVisual()" v-show="baseData.isOpen != 1 && visualStatus == 0">{{ $root.lang.userinfo.enterprise.toApply }}</el-button>
          <el-button class="pull-right edit-button" type="primary" @click="toBuyVisual()" v-show="baseData.isOpen != 1 && visualStatus == 3">{{ $root.lang.userinfo.personal.toBuy }}</el-button>
        </el-form-item>
        <el-form-item :label="getLabelEnterprise('auditStatus')">
          <template slot-scope="scope">
            <p>{{ baseState.auditStatus, baseData.auditStatus, "--" | matchValue }}</p>
          </template>
        </el-form-item>
        <el-form-item :label="getLabelEnterprise('auditDesc')" v-show="baseData.auditStatus == 2">
          <span>{{ baseData.auditDesc | dataFormat }}</span>
        </el-form-item>
        <el-form-item :label="getLabelEnterprise('joshid')" v-show="baseData.isOpen == 1">
          <span>{{ joshId | dataFormat }}</span>
          <el-button class="pull-right edit-button" type="primary" @click="initJoshId()" v-show="joshId == null || joshId == ''">{{ $root.lang.userinfo.enterprise.create }}</el-button>
        </el-form-item>
        <el-form-item :label="getLabelEnterprise('joshkey')" v-show="baseData.isOpen == 1">
          <span>{{ joshKey | dataFormat }}</span>
          <!-- <el-button class="pull-right edit-button" type="primary" @click="updateJoshKey()">{{ joshKey == null ? $root.lang.userinfo.enterprise.create : $root.lang.userinfo.enterprise.update }}</el-button> -->
        </el-form-item>
      </el-form>
    </div>

    <EditStock :show="showEdit" :type="type" @editReceive="getReceive" @reload="reloadTable" />
    <EditVisualStock :show="showVisualEdit" :type="type" @editReceive="getReceive" @reload="reloadTable" />
    <EditBlockStock :show="showBlockEdit" @editReceive="getReceive" @reload="reloadTable" />
    <BuyLog :show="showBuyLog" @editReceive="getReceive" @reload="toQr" />
    <QrShow :show="showQr" :qrUrl="qrUrl" @editReceive="getReceiveQr"/>

	</div>
</template>

<script>
import '@/options/baseState';
import EditStock from './components/editStock'
import EditVisualStock from './components/editVisualStock'
import EditBlockStock from './components/editBlockStock'
import BuyLog from './components/buyLog'
import QrShow from './components/qrShow'

export default {
	name: 'User',
	data() {
		return {
      baseState: baseState,
      fullscreenLoading: true,
      baseData: {},
      addDeviceNum: '',
      installAppNum: '',
      joshId: '',
      joshKey: '',
      formLabelWidth: '140px',
      isPersonal: true,
      showEdit: false,
      showVisualEdit: false,
      type: null,
      visualStatus: 0,
      blockStatus: null,
      showBlockEdit: false,
      blockNum: 0,
      logStatus: null,
      logExpireTime: null,
      showBuyLog: false,
      showQr: false,
      qrUrl: null,
      orderNo: null,
      interval: null,
      payTip: '请尽快支付',
    }
	},
  components: {
    EditStock, EditVisualStock, EditBlockStock, BuyLog, QrShow
  },
  watch:{
  },
  methods: {
    getLabelPersonal(name) {
      return this.$root.lang.userinfo.personal[name]+'：'
    },
    getLabelEnterprise(name) {
      return this.$root.lang.userinfo.enterprise[name]+'：'
    },
    //获取个人信息
    getUserInfo() {
      this.fullscreenLoading = true
			this.request({
        url: '/system/user/info/' + this.Cookies.get('I'),
        method: 'get',
      }).then(response => {
        this.baseData = response.result
        this.visualStatus = this.Cookies.get('V')
        this.blockStatus = this.Cookies.get('B')
        this.logStatus = this.Cookies.get('L')
        this.logExpireTime = this.Cookies.get('M')
        this.getInstallAppNum()
        if(response.result.accountType == 1) {
          this.isPersonal = true
          this.getAddDeviceNum()
        } else {
          this.isPersonal = false
          if(response.result.isOpen == 1) {
            this.getJoshIdKey()
          }
        }
        if(this.blockStatus == 3) {
          this.getBlockNum()
        }
        this.fullscreenLoading = false
      }).catch(error => {
        this.fullscreenLoading = false
        this.$message({
          message: error.errmsg,
          type: 'error',
          duration: 3 * 1000
        })
      })
		},
    initJoshId() {
			this.request({
        url: '/system/secret/init',
        method: 'get',
      }).then(response => {
        this.joshid = response.result
      }).catch(error => {
        this.$message({
          message: error.errmsg,
          type: 'error',
          duration: 3 * 1000
        })
      })
		},
    updateJoshKey() {
			this.request({
        url: '/system/secret/update',
        method: 'get',
      }).then(response => {
        this.joshKey = response.result
      }).catch(error => {
        this.$message({
          message: error.errmsg,
          type: 'error',
          duration: 3 * 1000
        })
      })
		},
    getJoshIdKey() {
      this.fullscreenLoading = true
			this.request({
        url: '/system/secret/get',
        method: 'get',
      }).then(response => {
        this.joshId = response.result.joshId
        this.joshKey = response.result.joshKey
        this.fullscreenLoading = false
      }).catch(error => {
        this.fullscreenLoading = false
        // this.$message({
        //   message: error.errmsg,
        //   type: 'error',
        //   duration: 3 * 1000
        // })
      })
		},
    //获取用户剩余可安装应用的次数
    getInstallAppNum() {
      this.fullscreenLoading = true
			this.request({
        url: '/application/issue/stock',
        method: 'get',
      }).then(response => {
        this.installAppNum = response.result.all - response.result.other
        this.fullscreenLoading = false
      }).catch(error => {
        this.fullscreenLoading = false
        this.$message({
          message: error.errmsg,
          type: 'error',
          duration: 3 * 1000
        })
      })
		},
    //获取用户剩余可安装应用的次数
    getAddDeviceNum() {
      this.fullscreenLoading = true
			this.request({
        url: '/device/stock',
        method: 'get',
      }).then(response => {
        this.addDeviceNum = response.result.all - response.result.other
        this.fullscreenLoading = false
      }).catch(error => {
        this.fullscreenLoading = false
        this.$message({
          message: error.errmsg,
          type: 'error',
          duration: 3 * 1000
        })
      })
		},
    getBlockNum() {
      this.request({
        url: '/blockchain/stock/user/query',
        method: 'get',
      }).then(response => {
        this.blockNum = response.result.userStock
        this.fullscreenLoading = false
      }).catch(error => {
				this.fullscreenLoading = false
      })
    },
    getUserLog() {
      this.request({
        url: '/daliy/state',
        method: 'get',
      }).then(response => {
				if(response.result == null) {
          this.logStatus = null
          this.Cookies.set('L', null)
				} else {
          this.logStatus = response.result.auditState
          this.logExpireTime = response.result.effectiveTime
					this.Cookies.set('L', response.result.auditState)
					this.Cookies.set('M', response.result.effectiveTime)
				}
      }).catch(error => {
        this.logStatus = null
        this.Cookies.set('L', null)
      })
    },
    checkLang() {
      let langType = this.$root.getStorage('lang')
      if(langType == 'en') {
        this.baseState = enBaseState
      } else {
        this.baseState = baseState
      }
    },
    toBuy(type) {
      this.showEdit = true
      this.type = type
    },
    getReceive(data) {
      this[data.key] = data.value
    },
    getReceiveQr(data) {
      this[data.key] = data.value
      this.closeOrder(this.orderNo)
    },
    reloadTable() {
      this.getUserInfo()
    },
    toApplyVisual() {
      this.request({
        url: '/web/stock/application',
        method: 'get',
      }).then(response => {
        this.$message({
          message: this.$root.lang.userinfo.enterprise.applyTip,
          type: 'success',
          duration: 3 * 1000
        })
      }).catch(error => {
        this.$message({
          message: error.errmsg,
          type: 'error',
          duration: 3 * 1000
        })
      })
    },
    toBuyVisual() {
      this.showVisualEdit = true
    },
    toApplyBlock() {
      this.request({
        url: '/blockchain/stock/apply',
        method: 'get',
      }).then(response => {
        this.$message({
          message: this.$root.lang.userinfo.personal.applyTip,
          type: 'success',
          duration: 3 * 1000
        })
      }).catch(error => {
        this.$message({
          message: error.errmsg,
          type: 'error',
          duration: 3 * 1000
        })
      })
    },
    toBuyBlock() {
      this.showBlockEdit = true
    },
    toDownload() {
      this.$confirm(this.$root.lang.confirm.downloadBlockFile, this.$root.lang.confirm.tips, {
        confirmButtonText: this.$root.lang.confirm.downloadImmediately,
        cancelButtonText: this.$root.lang.confirm.noDownload,
        type: 'warning'
      }).then(() => {
        this.request({
          url: '/blockchain/secretkey/setting/download',
          method: 'get',
          responseType: "blob"
        }).then(response => {
          // 创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
          let blob = new Blob([response.data], {type: response.data.type});
          // 创建一个a标签
          const link = document.createElement('a')
          // 设置a标签的下载属性
          link.download = 'blockchain.json';
          // 将a标签设置为隐藏
          link.style.display = 'none';
          // 把之前处理好的地址赋给a标签的href
          link.href = URL.createObjectURL(blob);
          // 将a标签添加到body中
          document.body.appendChild(link);
          // 执行a标签的点击方法
          link.click();
          // 下载完成释放URL对象
          URL.revokeObjectURL(link.href)
          // 移除a标签
          document.body.removeChild(link)
        }).catch(error => {
          this.$message({
            message: error.errmsg,
            type: 'error',
            duration: 3 * 1000
          })
        })
      }).catch(() => {
      }) 
    },
    toApplyLog() {
      this.request({
        url: '/daliy/apply',
        method: 'get',
      }).then(response => {
        this.$message({
          message: this.$root.lang.userinfo.personal.applyTip,
          type: 'success',
          duration: 3 * 1000
        })
      }).catch(error => {
        this.$message({
          message: error.errmsg,
          type: 'error',
          duration: 3 * 1000
        })
      })
    },
    toBuyLog() {
      this.showBuyLog = true
    },
    toQr(param) {
      this.showQr = true
      this.qrUrl = param.qrCodeUrl
      this.orderNo = param.orderNo
      this.payTip = '请尽快支付'
      let self = this
      let i = 0;
      this.interval = setInterval(function() {
        self.queryOrder(self.orderNo)
        i = i + 1
        if(i >= 12) {
          // 关闭订单（两分钟未支付）
          self.closeOrder(self.orderNo)
        }
      }, 10 * 1000);
    },
    queryOrder(orderNo) {
      this.request({
        url: '/payment/wechart/query-order?outTradeNo=' + orderNo,
        method: 'get',
      }).then(response => {
        // 支付成功，关掉定时器，还需要关闭订单吗
        if(response.result.orderState == 'SUCCESS') {
          clearInterval(this.interval)
          this.showQr = false
          this.$message({
            message: '支付成功',
            type: 'success',
            duration: 10 * 1000
          })
          this.getUserLog()
        } else if(response.result.orderState == 'CLOSED' || response.result.orderState == 'PAYERROR'
                  || response.result.orderState == 'FAILED' || response.result.orderState == 'ERROR') {
          clearInterval(this.interval)
          this.showQr = false
          this.$message({
            message: response.result.orderStateDesc,
            type: 'error',
            duration: 10 * 1000
          })
        }
      }).catch(error => {
        this.$message({
          message: error.errmsg,
          type: 'error',
          duration: 3 * 1000
        })
      })
    },
    closeOrder(orderNo) {
      this.request({
        url: '/payment/wechart/close-order?outTradeNo=' + orderNo,
        method: 'get',
      }).then(response => {
        this.payTip = '二维码已失效，请重新购买'
        clearInterval(this.interval)
      }).catch(error => {
      })
    }
  },
  created() {
    this.getUserInfo()
    this.checkLang()
  }

}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
	.padding-container {
		text-align:left;
		.title-part {
			text-align: left;
			font-size: 18px;
			padding-bottom: 20px;
		}
    .tab-pan {
      min-width:460px;
    }
		.edit-email {
			margin-left:30px;
		}
    .back-btn {
      width: 43%;
    }
    .edit-button {
      min-width:100px;
    }
    .tips {
      padding-left: 100px;
      line-height: 30px;
    }
    .page-back {
      margin-top: -30px;
    }
    .form-item-tip {
      float: left;
    }
    .form-captcha {
      .el-input{
        display: inline-block;
        width: 76%;
        float: left;
      }
      img {
        height: 32px;
        border-radius: 4px;
        cursor: pointer;
        float: left;
        margin-left: 8px;
      }
    }

		.el-dialog {
		  transform: none;
		  left: 0;
		  position: relative;
		  margin: 0 auto;
		}
    .upload-part {
      margin-left:300px;
      display: inline-block;
      vertical-align: top;
      text-align: center;
    }
    .img-pic {
      width:100px;
      height:100px;
      border-radius:100px;
      border:1px solid #ccc;
      margin-bottom: 20px;
      overflow:hidden;
    }
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }
    .avatar {
      width: 100px;
      height: 100px;
      display: block;
      margin-bottom:15px;
      border-radius: 100px;
    }




    .cropper-content{
      display: flex;
      display: -webkit-flex;
      justify-content: flex-end;
      -webkit-justify-content: flex-end;
      .cropper{
        width: 350px;
        height: 300px;
      }
      .show-preview{
        flex: 1;
        -webkit-flex: 1;
        display: flex;
        display: -webkit-flex;
        justify-content: center;
        -webkit-justify-content: center;
        .preview{
          overflow: hidden;
          border-radius: 50%;
          border:1px solid #cccccc;
          background: #cccccc;
          margin-left: 40px;
        }
      }
    }
    .footer-btn{
      margin-top: 30px;
      display: flex;
      display: -webkit-flex;
      justify-content: flex-end;
      -webkit-justify-content: flex-end;
      .scope-btn{
        width: 350px;
        display: flex;
        display: -webkit-flex;
        justify-content: space-between;
        -webkit-justify-content: space-between;
        align-items: center;
      }
      .upload-btn{
        flex: 1;
        -webkit-flex: 1;
        display: flex;
        display: -webkit-flex;
        justify-content: center;
        -webkit-justify-content: center;
      }
      .upload {
        background-color: #3a8ee6;
        border: none;
        color: #fff;
        border-radius: 4px;
        width: 100px;
        margin-left: 40px;
      }
      .btn {
        outline: none;
        display: inline-block;
        white-space: nowrap;
        cursor: pointer;
        -webkit-appearance: none;
        text-align: center;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        outline: 0;
        margin: 0;
        -webkit-transition: .1s;
        transition: .1s;
        font-weight: 500;
        padding: 8px 15px;
        font-size: 12px;
        border-radius: 3px;
        color: #fff;
        background-color: #67c23a;
        border-color: #67c23a;
      }
    }

	}
</style>